package com.L.yygh.cmn.service.impl;

import com.L.yygh.cmn.listener.DictExcellListener;
import com.L.yygh.cmn.mapper.DictMapper;
import com.L.yygh.cmn.service.DictService;
import com.L.yygh.common.result.Result;
import com.L.yygh.model.cmn.Dict;
import com.L.yygh.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildDictData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for (Dict dict : dicts) {
            Long dictId = dict.getId();
            Boolean b = hasChild(dictId);
            dict.setHasChildren(b);
        }
        return dicts;
    }

    //导出所有字典数据
    @Override
    public void exportDictExcel(HttpServletResponse response) {
        try {
            //设置响应信息，传输文件
            response.setContentType("application/x-excel");
            response.setCharacterEncoding("utf-8");
            //这里URLEncoder.encode可以防止中文乱码，当然和easyexcel没有关系
//            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            String fileName = "Dict";
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            //从数据库中查出所有的Dict数据
            //Dict -> DictEeVo
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictVo);
                dictVoList.add(dictVo);
            }

            //将DictEeVo 作 Excel 写出至Response输出流
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictExcel(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictExcellListener(baseMapper))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String s, String value) {
        if(StringUtils.isEmpty(s)){
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",s);
            Dict dict = baseMapper.selectOne(wrapper);
            Long parent_id = dict.getId();
            //根据parent_id和value进行查询
            Dict findDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parent_id)
                    .eq("value", value));
            return findDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应id
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        Long id = dict.getId();
        //根据id获取子节点
        List<Dict> childDictData = this.findChildDictData(id);
        return childDictData;

    }

    public Boolean hasChild(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
